package com.ruoyi.web.controller.system;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.OkHttpClientUtil;
import com.ruoyi.common.utils.PageUtils;
import com.ruoyi.system.domain.module.estate.Estate;
import com.ruoyi.system.domain.module.location.City;
import com.ruoyi.system.domain.module.location.Province;
import com.ruoyi.system.domain.module.property.Property;
import com.ruoyi.system.domain.system.SysNoticeGroup;
import com.ruoyi.system.service.module.estate.IEstateService;
import com.ruoyi.system.service.module.location.CityService;
import com.ruoyi.system.service.module.location.ProvinceService;
import com.ruoyi.system.service.module.property.IPropertyService;
import com.ruoyi.system.service.system.ISysNoticeGroupService;
import com.ruoyi.system.service.system.ISysUserService;
import com.ruoyi.web.controller.common.BaseController;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.system.domain.system.SysNotice;
import com.ruoyi.system.service.system.ISysNoticeService;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 公告 信息操作处理
 *
 * @author ruoyi
 */
@Validated
@RequiredArgsConstructor(onConstructor_ = @Autowired)
@RestController
@RequestMapping("/system/notice")
public class SysNoticeController extends BaseController {

    private final ISysNoticeService noticeService;
    private final IEstateService estateService;
    private final ISysUserService sysUserService;
	private final ProvinceService provinceService;
	private final IPropertyService propertyService;
	private final CityService cityService;
	private final ISysNoticeGroupService sysNoticeGroupService;

	@Value("${ruoyi.apiUrl}")
	private String apiUrl;


    /**
     * 获取通知公告列表
     */
    @PreAuthorize("@ss.hasAnyPermi('system:notice:list,module:notice:list')")
    @GetMapping("/list")
    public TableDataInfo<SysNotice> list(SysNotice notice) {
		QueryWrapper<SysNotice> qw = new QueryWrapper<>();
		SysUser sysUser = getUser();
		//用户类型 0 - 系统管理员  1 - 平台管理员 2 - 物业管理员  3 - 小区管理员   4 - 商家用户
		if(sysUser.getUserType() == 2){
			qw.eq("property_id",sysUser.getPropertyId());

			if(notice.getEstateId() != null){
				qw.eq("estate_id",notice.getEstateId());
			}

		} else if(sysUser.getUserType() == 3){
			qw.eq("estate_id",sysUser.getEstateId());
		}else{
			if(notice.getPropertyId() != null){
				qw.eq("property_id",notice.getPropertyId());
			}
			if(notice.getEstateId() != null){
				qw.eq("estate_id",notice.getEstateId());
			}
		}

		if(notice.getNoticeType() != null){
			qw.eq("notice_type",notice.getNoticeType());
		}

		if(StrUtil.isNotEmpty(notice.getNoticeTitle())){
			qw.like("notice_title",notice.getNoticeTitle());
		}
		if(notice.getNoticeGroupId()!=null){
			qw.like("notice_group_id",notice.getNoticeGroupId());
		}

		TableDataInfo<SysNotice> td = PageUtils.buildDataInfo(noticeService.page(PageUtils.buildPage(), qw));
		List<SysNotice> list = td.getRows();
		for (SysNotice list1:list){
			if (list1.getEstateId()!=null){
				Estate estate = estateService.findById(list1.getEstateId());
				if (estate!=null){
					list1.setEstateName(estate.getEstateName());
				}

			if (list1.getNoticeGroupId()!=null){
				SysNoticeGroup group = sysNoticeGroupService.findById(list1.getNoticeGroupId());
				if (group!=null){
					list1.setNoticeGroupName(group.getGroupName());
				}
			}
			}
		}
		Map<String,Object> map = new HashMap<>();
		map.put("userType",sysUser.getUserType());
		td.setOtherData(map);
        return td;
    }
	/**
	 * 获取通知列表
	 */
	@PreAuthorize("@ss.hasAnyPermi('system:notice:list,module:notice:list')")
	@GetMapping("/lists")
	public List<SysNotice> lists(SysNotice notice) {
		QueryWrapper<SysNotice> qw = new QueryWrapper<>();
		SysUser sysUser = getUser();
		//用户类型 0 - 系统管理员  1 - 平台管理员 2 - 物业管理员  3 - 小区管理员   4 - 商家用户
		if(sysUser.getUserType() == 2){
			qw.eq("property_id",sysUser.getPropertyId());

			if(notice.getEstateId() != null){
				qw.eq("estate_id",notice.getEstateId());
			}

		} else if(sysUser.getUserType() == 3){
			qw.eq("estate_id",sysUser.getEstateId());
		}else{
			if(notice.getPropertyId() != null){
				qw.eq("property_id",notice.getPropertyId());
			}
			if(notice.getEstateId() != null){
				qw.eq("estate_id",notice.getEstateId());
			}
		}

		if(notice.getNoticeType() != null){
			qw.eq("notice_type",notice.getNoticeType());
		}

		if(StrUtil.isNotEmpty(notice.getNoticeTitle())){
			qw.like("notice_title",notice.getNoticeTitle());
		}

		List<SysNotice> td = noticeService.list(qw);

		return td;
	}

    /**
     * 根据通知公告编号获取详细信息
     */
    @PreAuthorize("@ss.hasAnyPermi('system:notice:query,module:notice:query')")
    @GetMapping(value = "/{noticeId}")
    public AjaxResult getInfo(@PathVariable Long noticeId) {
		SysNotice notice = noticeService.selectNoticeById(noticeId);
		if(notice!=null){
			if(notice.getProvId()!=null && notice.getCityId()!=null){
				String[] areas = {String.valueOf(notice.getProvId()), String.valueOf(notice.getCityId())};
				notice.setProvinceArray(areas);
			}
			Property property = propertyService.findById(notice.getPropertyId());
			if(property != null){
				QueryWrapper<Estate> qw = new QueryWrapper<>();
				qw.eq("property_id", property.getId());
				List<Estate> estateList = estateService.list(qw);
				notice.setEstateList(estateList);
			}
		}
        return AjaxResult.success(notice);
    }

    /**
     * 新增通知公告
     */
    @PreAuthorize("@ss.hasAnyPermi('system:notice:add,module:notice:add')")
    @Log(title = "通知公告", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Validated @RequestBody SysNotice notice) {
        if(notice.getEstateId()!=null){
            Estate estate = estateService.findById(notice.getEstateId());
            if(estate!=null){
                notice.setPropertyId(estate.getPropertyId());
            }
        }
        if(notice.getCreateBy()!=null){
            SysUser sysUser= sysUserService.selectUserByUserName(notice.getCreateBy());
            if(sysUser.getUserType()==2){
                notice.setPropertyId(sysUser.getPropertyId());
            }
            if(sysUser.getUserType()==3){
                notice.setPropertyId(sysUser.getPropertyId());
                notice.setEstateId(sysUser.getEstateId());
            }
        }

		if(notice.getProvinceArray()!=null&&notice.getProvinceArray().length==2){
			notice.setProvId(Integer.parseInt(notice.getProvinceArray()[0]));
			notice.setCityId(Integer.parseInt(notice.getProvinceArray()[1]));

			Province province = provinceService.findById(notice.getProvinceArray()[0]);
			if(province!=null){
				notice.setProvName(province.getProvinceName());
			}

			City city = cityService.findById(notice.getProvinceArray()[1]);
			if(city!=null){
				notice.setCityName(city.getCityName());
			}
		}

        notice.setCreateBy(SecurityUtils.getUsername());
		int ret = noticeService.insertNotice(notice);
        if(ret > 0){
			OkHttpClientUtil.getInstance().getData(apiUrl + "redis/reset/notice");
		}
        return toAjax(ret);
    }

    /**
     * 修改通知公告
     */
    @PreAuthorize("@ss.hasAnyPermi('system:notice:edit,module:notice:edit')")
    @Log(title = "通知公告", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody SysNotice notice) {
        if(notice.getEstateId()!=null){
            Estate estate = estateService.findById(notice.getEstateId());
            if(estate!=null){
                notice.setPropertyId(estate.getPropertyId());
            }
        }
        notice.setUpdateBy(SecurityUtils.getUsername());

		if(notice.getProvinceArray()!=null&&notice.getProvinceArray().length==2){
			notice.setProvId(Integer.parseInt(notice.getProvinceArray()[0]));
			notice.setCityId(Integer.parseInt(notice.getProvinceArray()[1]));

			Province province = provinceService.findById(notice.getProvinceArray()[0]);
			if(province!=null){
				notice.setProvName(province.getProvinceName());
			}

			City city = cityService.findById(notice.getProvinceArray()[1]);
			if(city!=null){
				notice.setCityName(city.getCityName());
			}
		}
        int ret = noticeService.updateNotice(notice);
		if(ret > 0){
			OkHttpClientUtil.getInstance().getData(apiUrl + "redis/reset/notice");
		}
        return toAjax(ret);
    }

    /**
     * 删除通知公告
     */
    @PreAuthorize("@ss.hasAnyPermi('system:notice:remove,module:notice:remove')")
    @Log(title = "通知公告", businessType = BusinessType.DELETE)
    @DeleteMapping("/{noticeIds}")
    public AjaxResult remove(@PathVariable Long[] noticeIds) {
        return toAjax(noticeService.deleteNoticeByIds(noticeIds));
    }
}
